package com.charles.thread;

public class ThreadScopeShareData {
	public static void main(String[] args) {
		ShareData shareData = new ShareData();
		for (int i = 0; i < 2; i++) {
			new Thread(new Inc(shareData)).start();
			new Thread(new Dec(shareData)).start();
		}

		System.out.println(shareData.getI());
	}
}

class ShareData {
	private int i = 0;

	public int getI() {
		return i;
	}

	public void setI(int i) {
		this.i = i;
	}

	public synchronized void inc() {
		i++;
		System.out.println(Thread.currentThread().getName() + ": 加1， i的值为: " + getI());
	}

	public synchronized void dec() {
		i--;
		System.out.println(Thread.currentThread().getName() + ": 减1， i的值为: " + getI());
	}
}

class Inc implements Runnable {
	private ShareData shareData;

	@Override
	public void run() {
		for (int i = 0; i < 20; i++) {
			shareData.inc();

		}
	}

	public Inc(ShareData shareData) {
		this.shareData = shareData;
	}
}

class Dec implements Runnable {
	private ShareData shareData;

	@Override
	public void run() {
		for (int i = 0; i < 20; i++) {
			shareData.dec();

		}
	}

	public Dec(ShareData shareData) {
		this.shareData = shareData;
	}
}
